package com.novel.resource.cos.impl;

import com.novel.common.resource.IResourceService;
import com.novel.resource.minio.config.MinioConfig;
import io.minio.MinioClient;
import lombok.AllArgsConstructor;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * 资源存储服务实现类
 *
 * @author novel
 * @date 2020/1/3
 */
@AllArgsConstructor
public class MinioResourceServiceImpl implements IResourceService {
    /**
     * oss 操作客户端
     */
    private MinioClient minioClient;

    private MinioConfig minioConfig;
    /**
     * 文件访问连接最大超时时间
     */
    private int fileCacheMaxTime;

    @Override
    public String getFileUrl(String sourceUrl) throws IOException {
        try {
            return minioClient.getObjectUrl(minioConfig.getBucketName(), sourceUrl);
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    @Override
    public boolean upLoadFile(String sourceUrl, String destPath) throws IOException {
        try {
            minioClient.putObject(minioConfig.getBucketName(), destPath, sourceUrl);
        } catch (Exception e) {
            throw new IOException(e);
        }
        return true;
    }

    @Override
    public boolean upLoadFile(InputStream source, String destPath) throws IOException {
        try {
            minioClient.putObject(minioConfig.getBucketName(), destPath, source, source.available(), "application/octet-stream");
        } catch (Exception e) {
            throw new IOException(e);
        }
        return true;
    }

    @Override
    public void download(String filePath, String localPath) throws IOException {
        try {
            minioClient.getObject(minioConfig.getBucketName(), filePath, localPath);
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    @Override
    public boolean delete(String filePath) throws IOException {
        try {
            minioClient.removeObject(minioConfig.getBucketName(), filePath);
        } catch (Exception e) {
            throw new IOException(e);
        }
        return true;
    }

    @Override
    public byte[] readBytes(String filePath) throws IOException {
        try {
            InputStream inputStream = minioClient.getObject(minioConfig.getBucketName(), filePath);
            return IOUtils.toByteArray(inputStream);
        } catch (Exception e) {
            throw new IOException(e);
        }
    }
}
